//
//  LLCommentViewController.m
//  BestLearning
//
//  Created by apple on 2017/3/2.
//  Copyright © 2017年 apple. All rights reserved.
//

static NSString * const ID = @"LLCommentViewController";

#import "LLCommentViewController.h"
#import "LLExcellentCommentViewController.h"
#import "LLWellCommentViewController.h"
#import "LLGeneralCommentViewController.h"
#import "LLBadCommentViewController.h"
#import "ZYAddStrongCouseDetailFourModel.h"
#import "UIView+SEKExtension.h"
@interface LLCommentViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, weak)  UIView *titleView;
@property (nonatomic, strong) NSMutableArray *buttons;
@property (nonatomic, weak) UIButton *selectButton;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIView *underLineView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@end

@implementation LLCommentViewController

- (NSMutableArray *)dataSource {
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (self.isUp) {
         self.title = @"课程评论";
    }else{
         self.title = @"机构评论";
    }
   
    
    // 添加底部内容view
    [self setupBottomView];
    
    
//    if (self.isUp) {
//
//        [self setNetWorkTow];
//        [self setUpChildViewController];
//    }else{
//
           [self setUpChildViewController];
//    }
    
    //添加子控制器
 
    
    //设置标题View
    [self setUpTitleView];
    
    // 不需要自动添加额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
}



- (void)setNetWorkTow{
    
    
    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=getCommentData2&lessonId=%@&pageNumber=1&type=0",self.couseId];
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [NetManager Get:LLBaseURLs(url) Auth:YES Params:nil Success:^(id Obj) {
        [SVProgressHUD dismiss];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            
            NSDictionary *dict = [Obj valueForKey:@"t"];
            
            NSArray *arr  = [dict valueForKey:@"dataList"];
            
            for (NSDictionary *dic  in arr) {
                
                ZYAddStrongCouseDetailFourModel *model = [ZYAddStrongCouseDetailFourModel courseCommentModelWithDict:dic];
                
                
                [self.dataSource addObject:model];
            }
            
            
            
        }
        
    } Fail:^(NSError *Error) {
         [SVProgressHUD dismiss];
    }];
    
    
    
    
    
    
    
    
    
}




#pragma mark - 懒加载按钮数组
- (NSMutableArray *)buttons
{
    if (_buttons == nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}


- (void)setupBottomView
{
    // 布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //    layout.itemSize = [UIScreen mainScreen].bounds.size;
    layout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight);
    
    // 设置滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    // UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) collectionViewLayout:layout];
    
    collectionView.backgroundColor = [UIColor whiteColor];
 
    [self.view addSubview:collectionView];
    // 不显示水平指示器
    collectionView.showsHorizontalScrollIndicator = NO;
    // 开启分页
    collectionView.pagingEnabled = YES;
    _collectionView = collectionView;
    // 设置collectionView数据源,展示cell,需要把子控制器view添加cell
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.bounces = NO;
    
    // 注册cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}





#pragma mark -添加所有子控制器
- (void)setUpChildViewController {
    
    //区分各种评论
    //NSLog(@"%@",self.courseCommentModelArray);
    
    NSMutableArray *execellentArray = [NSMutableArray array];
    NSMutableArray *wellArray = [NSMutableArray array];
    NSMutableArray *generalArray = [NSMutableArray array];
    NSMutableArray *badArray = [NSMutableArray array];
    

   // NSMutableArray *arr;
//    if (self.isUp) {
//
//        arr = self.dataSource;
//    }else{
//
//        arr = self.courseCommentModelArray;
//    }
//
    
    
    
    
    for (int i = 0 ; i < self.courseCommentModelArray.count; i ++) {
        
        ZYAddStrongCouseDetailFourModel *model = self.courseCommentModelArray[i];
        
        //根据满意度 给各个数组赋值
        NSInteger satisfy = [model.satisfy integerValue];
        
        switch (satisfy) {
            case 4:{
                
                [execellentArray addObject:model];
            }
                break;
                
            case 3:{
                
                [wellArray addObject:model];
            }
                break;
            case 2:{
                
                [generalArray addObject:model];
            }
                break;
            case 1:{
             
                [badArray addObject:model];
            }
                break;
            default:
                break;
        }
        
        
    }
    
    
    //好评
    LLExcellentCommentViewController *excellentVC = [[LLExcellentCommentViewController alloc] init];
    excellentVC.title = @"好";
    excellentVC.isUp = self.isUp;
    excellentVC.ID = self.couseId;
    excellentVC.courseCommentModelArray = execellentArray;
    [self addChildViewController:excellentVC];
    

    //
    LLWellCommentViewController *wellVC = [[LLWellCommentViewController alloc] init];
    wellVC.title = @"良";
    wellVC.courseCommentModelArray = wellArray;
    wellVC.isUp = self.isUp;
     wellVC.ID = self.couseId;
    [self addChildViewController:wellVC];
    
    
    //
    LLGeneralCommentViewController *generalVC = [[LLGeneralCommentViewController alloc] init];
    generalVC.title = @"普";
    generalVC.courseCommentModelArray = generalArray;
     generalVC.ID = self.couseId;
    generalVC.isUp = self.isUp;
    [self addChildViewController:generalVC];
    
    
    //
    LLBadCommentViewController *badVC = [[LLBadCommentViewController alloc] init];
    badVC.title = @"差";
    badVC.courseCommentModelArray = badArray;
     badVC.ID = self.couseId;
    badVC.isUp = self.isUp;
    [self addChildViewController:badVC];
    
    
}


#pragma mark -添加标题View
- (void)setUpTitleView {
    
    CGFloat titleViewX = 40;
    CGFloat titleViewY = 0;
    CGFloat titleViewW = kScreenWidth  - 80;
    CGFloat titleViewH = 44;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(titleViewX, titleViewY, titleViewW, titleViewH)];
    self.titleView = titleView;
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    
    NSInteger count = self.childViewControllers.count;
    CGFloat titleBtnW = (kScreenWidth - 80) / count;
    CGFloat titleBtnH = titleView.height;
    CGFloat titleBtnX = 0;
    CGFloat titleBtnY = 0;
    for (int i = 0; i < count; i++) {
        
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.tag = i;
        UIViewController *vc = self.childViewControllers[i];
        [titleBtn setTitle:vc.title forState:UIControlStateNormal];
        [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [titleBtn setTitleColor:ColorRGB(139, 198, 253) forState:UIControlStateSelected];
        titleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        titleBtnX = titleBtnW * i;
        titleBtn.frame = CGRectMake(titleBtnX, titleBtnY, titleBtnW, titleBtnH);
        [titleView addSubview:titleBtn];
        [self.buttons addObject:titleBtn];
        // 监听按钮
        [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //在这设置button初始的选择状态
        if (i == 0) {
            
            // 添加下划线
            UIView *underLineView = [[UIView alloc] init];
            underLineView.backgroundColor = ColorRGB(139, 198, 253);
            [titleView addSubview:underLineView];
            _underLineView = underLineView;
            
            // 中心点x
            underLineView.height = 2;
            underLineView.y = titleView.height - underLineView.height;
            // 1.根据控件内容计算尺寸,然后给控件设置尺寸
            [titleBtn.titleLabel sizeToFit];
            underLineView.width = titleBtn.titleLabel.width + 50;
            // 一定要先设置尺寸 在设置中心点
            underLineView.centerX = titleBtn.centerX;
            
            [self titleClick:titleBtn];
        }
        
        
    }
}


#pragma mark - 选中按钮
- (void)selButton:(UIButton *)button
{
    //重复点击同一个按钮 刷新页面
    //if (_selectButton == button) {
    //    NSString *selectRefreshController = [NSString stringWithFormat:@"refreshView%ld",(long)button.tag];
    //    NSNotification * refresh = [NSNotification notificationWithName:selectRefreshController object:nil userInfo:@{@"tag":@"123"}];
    //    [[NSNotificationCenter defaultCenter] postNotification:refresh];
    //}
    _selectButton.selected = NO;
    button.selected = YES;
    _selectButton = button;
    
    // 修改下划线位置
    [UIView animateWithDuration:0.25 animations:^{
        _underLineView.centerX = button.centerX;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }];
    
}

#pragma mark - 点击标题
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    // 1.选中按钮
    [self selButton:button];
    
    // 2.设置collectionView偏离量
    CGFloat offsetX = i * kScreenWidth;
    _collectionView.contentOffset = CGPointMake(offsetX, 0);
}


#pragma mark - UICollectionViewDelegate
// 滚动完成的时候就会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 获取页码
    NSInteger page = scrollView.contentOffset.x / kScreenWidth;
    
    // 获取标题按钮
    UIButton *titleButton = self.buttons[page];
    
    // 选中标题
    [self selButton:titleButton];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.childViewControllers.count;
}

// 只要有新的cell出现就会调用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    // 移除其它子控制器view
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 添加对应的子控制器view 到 对应cell
    UIViewController *vc = self.childViewControllers[indexPath.row];
    // 添加到contentView
    [cell.contentView addSubview:vc.view];
    
    //    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    //
    return cell;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [SVProgressHUD dismiss];
    
}

@end
